import React, { useState } from "react";
import { Button, Popover, Space } from "antd";
import {
  LeftOutlined,
  PlusCircleOutlined,
  RightOutlined,
} from "@ant-design/icons";
import styles from "./style.less";
import dayjs from "dayjs";

const HOURS_ARR = [
  "9:00 - 10:00",
  "10:00 - 11:00",
  "11:00 - 12:00",
  "12:00 - 13:00",
  "13:00 - 14:00",
  "14:00 - 15:00",
  "15:00 - 16:00",
  "16:00 - 17:00",
  "17:00 - 18:00",
  "18:00 - 19:00",
  "19:00 - 20:00",
];

const WeekTable: React.FC = (props) => {
  const [currentDate, setCurrentDate] = useState(new Date());
  const {
    nickName,
    title,
    onAddClick,
    cellItem,
    onCellItemClick,
    resetDate,
    dayOff,
    editInfo,
    onPreWeek,
    onNextWeek,
    deleteItem,
  } = props;
  const getWeekRangeArray = (date) => {
    const result = [];
    // 获取当前日期的时间戳
    const timestamp = date.getTime();
    // 获取当前日期是星期几 (0 是星期日，1 是星期一，以此类推)
    const dayOfWeek = date.getDay();
    // 计算当前日期所在周的第一天的时间戳
    const firstDayTimestamp = timestamp - dayOfWeek * 24 * 60 * 60 * 1000;
    // 生成当前这一周的日期数组
    for (let i = 0; i < 7; i++) {
      const dayTimestamp = firstDayTimestamp + i * 24 * 60 * 60 * 1000;
      const day = new Date(dayTimestamp);
      const formattedDay = day.toISOString().split("T")[0]; // 格式化日期为 'YYYY-MM-DD'

      const dayOfWeek = day.getDay();
      const daysOfWeek = [
        "Sunday",
        "Monday",
        "Tuesday",
        "Wednesday",
        "Thursday",
        "Friday",
        "Saturday",
      ];
      const formattedDayOfWeek = daysOfWeek[dayOfWeek];

      result.push({
        date: formattedDay,
        dayOfWeek: formattedDayOfWeek,
      });
    }
    return result;
  };

  const getDuringDate = (dayOff = [], paramDay, paramTimes) => {
    let duringDays = dayOff.filter((day) => {
      let { startTime, endTime } = day;
      let [start, end] = paramTimes.split(" - ");
      const startDay = Date.parse(`${paramDay} ${start}`),
        endDay = Date.parse(`${paramDay} ${end}`),
        startDate = Date.parse(startTime),
        endDate = Date.parse(endTime);

      if (!(endDate <= startDay || endDay <= startDate)) {
        return true;
      }
    });

    if (duringDays.length) {
      let start = dayjs(duringDays[0].startTime).format("HH:mm"),
        end = dayjs(duringDays[0].endTime).format("HH:mm");
      return (
        <Popover
          content={
            <div>
              <div>员工名称：{nickName}</div>
              <div>当前日期：{paramDay}</div>
              <div>时间段： {`${start} - ${end}`}</div>
              <div>状态：{duringDays[0].holidayType === "3" ? "休息" : ""}</div>
              <div>设置人: {duringDays[0].createBy}</div>
              <div>设置日期: {duringDays[0].createTime}</div>
              <Space>
                <Button type="link" onClick={() => deleteItem(duringDays[0])}>
                  撤销
                </Button>
                <Button type="link" onClick={() => editInfo(duringDays[0])}>
                  编辑
                </Button>
              </Space>
            </div>
          }
          title=""
        >
          <div className="full-bg holiday">休息</div>
        </Popover>
      );
    }
  };

  const calcTableDate = (dateParams) => {
    let arr = [
      {
        date: "时间段",
        hours: HOURS_ARR,
      },
    ];
    for (let i = 0; i < getWeekRangeArray(dateParams).length; i++) {
      arr.push({
        date: getWeekRangeArray(dateParams)[i].date,
        dayOfWeek: getWeekRangeArray(dateParams)[i].dayOfWeek,
        hours: HOURS_ARR,
      });
    }
    return arr;
  };

  const getWeekFirstDay = (inputDate, isPrevious) => {
    const currentDate = new Date(inputDate);
    const dayOfWeek = currentDate.getDay();
    const firstDayTimestamp =
      currentDate.getTime() -
      dayOfWeek * 24 * 60 * 60 * 1000 +
      (isPrevious ? -7 : 7) * 24 * 60 * 60 * 1000;
    const firstDayOfPreviousWeek = new Date(firstDayTimestamp);
    return firstDayOfPreviousWeek.toISOString().split("T")[0]; // 返回 'YYYY-MM-DD' 格式的字符串
  };

  // console.log(calcTableDate(currentDate))

  const renderItemByType = (type) => {
    switch (type) {
      case "reset":
        return;
    }
  };

  return (
    <div className={styles.table}>
      <div className="header">
        <Button
          type="link"
          icon={<LeftOutlined />}
          onClick={() => {
            onPreWeek && onPreWeek();
            let preDay = getWeekFirstDay(currentDate, true);
            setCurrentDate(new Date(preDay));
          }}
        >
          上一页
        </Button>
        <div className="title">{title || "张三 （xxxx场馆 2）"}</div>
        <Button
          type="link"
          className="right"
          icon={<RightOutlined />}
          onClick={() => {
            onNextWeek && onNextWeek();
            let preDay = getWeekFirstDay(currentDate, false);
            setCurrentDate(new Date(preDay));
          }}
        >
          下一页
        </Button>
      </div>
      <div className="content">
        <div className="main">
          {/*<div className='cell'>时间段</div>*/}
          {calcTableDate(currentDate).map(({ date, hours }, k) => {
            return (
              <div className="cell" key={k}>
                <div className="cell-header">
                  <div>{date}</div>
                  {k !== 0 && (
                    <div className="fixed-center">
                      <span>工作</span>{" "}
                      <PlusCircleOutlined
                        style={{
                          color: "#5ac1b0",
                          fontSize: "16px",
                          verticalAlign: "center",
                        }}
                        onClick={() => onAddClick && onAddClick(date)}
                      />{" "}
                    </div>
                  )}
                </div>
                {hours.map((v, key) => (
                  <div className="cell-content" key={key}>
                    {k === 0 ? (
                      v
                    ) : (
                      <div
                        className="full-bg"
                        onClick={() =>
                          onCellItemClick &&
                          onCellItemClick({
                            time: v,
                            date,
                          })
                        }
                      >
                        {getDuringDate(dayOff, date, v)}
                      </div>
                    )}
                  </div>
                ))}
              </div>
            );
          })}
        </div>
      </div>
    </div>
  );
};

export default WeekTable;
